function [cInt,cArea,cPx] = extractMetrics(I,BW,s,channels,positions,time,area_min,area_max)

%% rewrite this, using builtin regionprops, structured output, save separate from images

%% INPUT Defaults
if nargin < 8 || isempty(area_max)
    area_max = 512*512/3; %flood
end
if nargin < 7 || isempty(area_min)
    area_min = 20; %single cell
end
if nargin < 6 || isempty(time)
    time = 1:size(I{1,1},3); %all
end
if nargin < 5 || isempty(positions)
    positions = 1:size(I,2); %all
end
if nargin < 4 || isempty(channels)
    channels = [2 3]; %R/G only
end

h_bar = waitbar(0,'Quantifying Features...');
%Def
if s.z==1 % 2D
    conn = 8;
else % 3D
    conn = 26;
end

for p=positions
    for t=time
        %Clear each 2D border -- make sure this does not clear time ends
        %nor z ends
        BW{c,p} = imclearborder(BW{c,p},4);
        
        %Clear away objects that are not present in start/end frames
        BW{c,p} = BW{c,p} &~ imclearborder(BW{c,p},conn);
        %Cluster masks from combined Red/Green fluorescent channels
        cc = bwconncomp(BW{s.channel_name_std=='R',p}(:,:,:,t) ...
            | BW{s.channel_name_std=='G',p}(:,:,:,t),conn);
        lcc = labelmatrix(cc);
        cellstats = regionprops(cc,'Area');
        area = cell2mat({cellstats.Area}');
        indices = 1:numel(area);
        %Area operations should already be handled with bwopen in 2d or 3d
        %Set min area cutoff
        indices(area<area_min)=[];
        %Set max area cutoff (e.g. flooded frame)
        indices(area>area_max)=[];
        if isempty(area)
            ['No objects detected in p=' num2str(p) ', t=' num2str(t)]
            return
        end
        for i=1:numel(indices)
            for c=channels
                cPx{c,p,i}(:,:,t) = I{c,p}(:,:,t) .* uint16(lcc==indices(i));
                cInt(c,p,i,t) = sum(sum(cPx{c,p,i}(:,:,t)));
                cArea(c,p,i,t) = area(indices(i));
            end
        end
        %Status
        waitbar(sum([p-1 t].*[numel(time) 1])/prod([numel(positions) numel(time)]),h_bar)
        clear cc lcc
    end
end
cInt(cInt==0)=NaN;
cArea(cArea==0)=NaN;
close(h_bar)

end